package com.example.controller.buyer;

import com.example.dto.TradeDTO;
import com.example.entity.Order;
import com.example.entity.enums.OrderStatusEnum;
import com.example.param.OrderSearchParams;
import com.example.service.OrderService;
import com.example.service.UserService;
import com.example.util.RedisUtil;
import com.example.vo.LoginUser;
import com.example.vo.Result;
import com.example.vo.ResultCode;
import com.example.vo.SubmitOrderResponseVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import static com.example.vo.ResultCode.*;

/**
 * @author circle48
 */
@RestController
@Api(tags = "买家端,订单接口")
@RequestMapping("/buyer/order")
public class OrderBuyerController {
    @Resource
    private OrderService orderService;

    @Resource
    private UserService userService;

    @Autowired
    private RedisUtil redisUtil;

    @ApiOperation(value = "查询用户订单列表")
    @GetMapping("/myOrder")
    public Result queryMyOrder(OrderSearchParams orderSearchParams) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long id = loginUser.getUser().getId();
//        long userID=1;
        return orderService.getMyOrders(id,orderSearchParams);
    }


    @ApiOperation(value = "用户下订单")
    @PostMapping("/createOrder")
    public Result createOrder(@RequestBody TradeDTO trade) {
        //System.out.println("用户下订单 trade = " + trade);
        try {
            SubmitOrderResponseVo responseVo = orderService.createOrder(trade);
            Integer code = responseVo.getCode();
            if (code == 0) {
                return Result.ok(responseVo);
            } else {
                switch (code) {
                    case 1:
                        return Result.error(TOKEN_VERIFICATION_FAILED);
                    case 2:
                        return Result.error(PRICE_CHANGED);
                    case 3:
                        return Result.error(NO_STOCK_AVAILABLE);
                    default:
                        return Result.error(SYSTEM_B0001);
                        // 假设 UNKNOWN_ERROR 是一个已定义的错误常量
                }
            }
        } catch (Exception e) {
            return Result.error(SYSTEM_B0101);
        }
    }

    @ApiOperation(value = "用户获取结算页订单数据")
    @GetMapping("/data")
    public Result<TradeDTO> getOrderData(@RequestParam("orderKey") String orderKey) {
        Object result = redisUtil.get(orderKey);
        if (result != null) {
            TradeDTO trade = (TradeDTO) result;
            return Result.ok(trade);
        } else {
            return Result.error(ResultCode.ORDER_NOT_FOUND);
        }
    }


    @ApiOperation(value = "确认收货")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderSn", value = "订单编号", required = true, paramType = "path")
    })
    @PostMapping(value = "/{orderSn}/receiving")
    public Result receiving(@NotNull(message = "订单编号不能为空") @PathVariable("orderSn") String orderSn) {
        Order order = orderService.getBySn(orderSn);
        if (order == null) {
            return Result.error(ResultCode.ORDER_NOT_EXIST);
        }
        //判定是否是待收货状态
        if (!order.getStatus().equals(OrderStatusEnum.WAIT_RECEIVE)) {
            return Result.error(ResultCode.ORDER_DELIVERED_ERROR);
        }
        // 判定是否是未确认收货状态
        if (order.getConfirmStatus() == 1) {
            return Result.error(ResultCode.ORDER_ALREADY_CONFIRMED);
        }
        orderService.receiving(orderSn);
        return Result.ok();
    }

}
